package com.lovesher.payment.web.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.lovesher.payment.common.enums.NotifyMethod;
import com.lovesher.payment.common.enums.PayStatus;
import com.lovesher.payment.common.enums.PayType;
import com.lovesher.payment.common.resposity.bean.PaymentSerial;
import com.lovesher.payment.common.service.ResubmitService;
import com.lovesher.payment.service.resposity.bean.PaymentInterface;
import com.lovesher.payment.service.resposity.dao.PaymentSerialDao;
import com.lovesher.payment.service.resposity.dao.PluginConfigDao;

@Controller("paymentController")
@RequestMapping("/payment")
public class PaymentController{

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private PaymentSerialDao paymentSerialDao;

	@Autowired
	private PluginConfigDao pluginConfigDao;
	
	@Autowired
	private ResubmitService resubmitService;
	/**
	 * 通知
	 */
	@RequestMapping("/notify/{notifyMethod}/{orderSn}/{userId}")
	@ResponseBody
	public String notify(@PathVariable NotifyMethod notifyMethod, @PathVariable String orderSn, @PathVariable Long userId, HttpServletRequest request, ModelMap model) {
		logger.info("notify start..... orderSn:" + orderSn);
		logger.info("request info:" + JSON.toJSONString(request.getParameterMap()));
		PaymentSerial paymentSerial = this.paymentSerialDao.findByOrderSnAndType(orderSn, userId,PayType.RECHARGE.getValue());
		if (paymentSerial == null) {
			paymentSerial = this.paymentSerialDao.findByOrderSnAndType(orderSn, userId,PayType.SHOPPING.getValue());
			if (paymentSerial == null) {
				return "fail";
			}
		}
		/**查找相应的插件桩**/
		PaymentInterface paymentInterface = pluginConfigDao.getPaymentPlugin(paymentSerial.getPaymentMethod());
		if (paymentSerial.getStatus() == PayStatus.SUCCESS.getValue()) {
			return paymentInterface.getNotifyMessage(orderSn, notifyMethod, request);
		}
		/** 防重复通知 **/
		if(resubmitService.isReSubmitForCommon(PaymentController.class.getName(), orderSn, "notify", 3)){
			return paymentInterface.getNotifyMessage(orderSn, NotifyMethod.sync, request);
		};
		/**验证签名**/
		Map<String,Object> returnMap = paymentInterface.verifyNotify(paymentSerial.getTradeNo(), notifyMethod, request, paymentSerial);
		if ((Boolean) returnMap.get("success")) {
			logger.info("verifyNotify success orderSn:" + orderSn);
			/** 校验通过,修改相关状态 */
			if (notifyMethod == NotifyMethod.async){
				logger.info("进入充值回调方法！！！");
				paymentInterface.paySucess(paymentSerial, returnMap.get("returnText") == null ? null : returnMap.get("returnText").toString(),PayStatus.SUCCESS,request);
				return paymentInterface.getNotifyMessage(orderSn, notifyMethod, request);
			}
		}
		logger.info("verifyNotify failed orderSn:" + orderSn);
		return paymentInterface.getNotifyMessage(orderSn, NotifyMethod.sync, request);
	}
	
	
	/**
	 * 通知
	 */
	@RequestMapping("/refundNotify/{notifyMethod}/{orderSn}/{userId}")
	@ResponseBody
	public String refundNotify(@PathVariable NotifyMethod notifyMethod, @PathVariable String orderSn, @PathVariable Long userId, HttpServletRequest request, ModelMap model) {
		logger.info("refundNotify start..... orderSn:" + orderSn);
		logger.info("request info:" + JSON.toJSONString(request.getParameterMap()));
		PaymentSerial paymentSerial = this.paymentSerialDao.findByOrderSnAndType(orderSn, userId,PayType.REFUND.getValue());
		if (paymentSerial == null) {
			return "fail";
		}
		/**查找相应的插件桩**/
		PaymentInterface paymentInterface = pluginConfigDao.getPaymentPlugin(paymentSerial.getPaymentMethod());
		if (paymentSerial.getStatus() == PayStatus.SUCCESS.getValue()) {
			return paymentInterface.getNotifyMessage(orderSn, notifyMethod, request);
		}
		/** 防重复通知 **/
		if(resubmitService.isReSubmitForCommon(PaymentController.class.getName(), orderSn, "notify", 3)){
			return paymentInterface.getNotifyMessage(orderSn, NotifyMethod.sync, request);
		};
		/**验证签名**/
		Map<String,Object> returnMap = paymentInterface.verifyNotify(paymentSerial.getTradeNo(), notifyMethod, request, paymentSerial);
		if ((Boolean) returnMap.get("success")) {
			logger.info("verifyNotify success orderSn:" + orderSn);
			/** 校验通过,修改相关状态 */
			if (notifyMethod == NotifyMethod.async){
				logger.info("进入退款回调方法！！！");
				paymentInterface.paySucess(paymentSerial, returnMap.get("returnText") == null ? null : returnMap.get("returnText").toString(),PayStatus.SUCCESS,request);
				return paymentInterface.getNotifyMessage(orderSn, notifyMethod, request);
			}
		}else{
			logger.info("verifyNotify failed orderSn:" + orderSn + ":returnMap|" + JSON.toJSONString(returnMap));
		}
		
		return paymentInterface.getNotifyMessage(orderSn, NotifyMethod.sync, request);
	}
}
